﻿/*
   Copyright 2011 Softisis

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using FOM.Interfaces;

namespace FOM.Impl.Converters
{
    /// <summary>
    /// Converts a string in any number or enum according to the target type.
    /// 03/04/2016: Support of nullable
    /// </summary>
    /// <remarks>Copyright Softisis 2011-2016 (France)</remarks>
    public class StringToValueTypesConv : IConverter
    {
        public object Convert(MappingContext ctx)
        {
            var tmp = ctx.ObjectSrc as string;
            if (string.IsNullOrEmpty(tmp))
                return null;

            Type t = ctx.Tdst;
            bool isNullable=false;

            if (ctx.Tdst.IsGenericType && ctx.Tdst.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                t = Nullable.GetUnderlyingType(ctx.Tdst);
            }

            object ret=ctx.ObjectDst;

            if (typeof(int) == t)
                ret = int.Parse(tmp);

            if (typeof(long) == t)
                ret = long.Parse(tmp);

            if (typeof(float) == t)
                ret = float.Parse(tmp);

            if (typeof(double) == t)
                ret = double.Parse(tmp);

            if (typeof(bool) == t)
                ret = bool.Parse(tmp);

            if (t.IsEnum)
                ret = Enum.Parse(t, tmp);

            return ret;
        }

        public IConverter Reverse()
        {
            return new ValueTypeToStringConv();
        }
    }
}
